package db

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"myblog/model"
)

var db *sql.DB

func InitDB(filePath string) {
	var err error
	db, err = sql.Open("sqlite3", filePath)
	if err != nil {
		log.Fatal(err)
	}

	createTableSQL := `CREATE TABLE IF NOT EXISTS posts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        author TEXT NOT NULL
    );`

	_, err = db.Exec(createTableSQL)
	if err != nil {
		log.Fatal(err)
	}
}

func GetPosts() ([]*model.BlogPost, error) {
	rows, err := db.Query("SELECT id, title, content, author FROM posts")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var posts []*model.BlogPost
	for rows.Next() {
		var post model.BlogPost
		if err := rows.Scan(&post.ID, &post.Title, &post.Content, &post.Author); err != nil {
			return nil, err
		}
		posts = append(posts, &post)
	}

	return posts, nil
}

func CreatePost(post model.BlogPost) (int64, error) {
	result, err := db.Exec("INSERT INTO posts (title, content, author) VALUES (?, ?, ?)", post.Title, post.Content, post.Author)
	if err != nil {
		return 0, err
	}

	return result.LastInsertId()
}

func GetPostByID(id int) (*model.BlogPost, error) {
	row := db.QueryRow("SELECT id, title, content, author FROM posts WHERE id = ?", id)

	var post model.BlogPost
	if err := row.Scan(&post.ID, &post.Title, &post.Content, &post.Author); err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}

	return &post, nil
}

func DeletePostByID(id int) error {
	_, err := db.Exec("DELETE FROM posts WHERE id = ?", id)
	return err
}

func UpdatePostByID(id int, post model.BlogPost) error {
	_, err := db.Exec("UPDATE posts SET title = ?, content = ?, author = ? WHERE id = ?", post.Title, post.Content, post.Author, id)
	return err
}
